package dale.web.user.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import dale.web.user.model.User;
import dale.web.user.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService service;

	@RequestMapping(value="/signIn", method=RequestMethod.GET)	
	public void signIn() {
	}
	
	@RequestMapping(value="/signOut", method=RequestMethod.GET)
	public void signOut() {
	}
	
	@RequestMapping(value="/signIn2", method=RequestMethod.GET)	
	public User signIn2() {
		return new User();
	}

	@RequestMapping(value="/signIn2", method=RequestMethod.POST)
	public String signIn2(@ModelAttribute @Validated User user, Errors errors, HttpSession session, Model model, @RequestParam(defaultValue="/") String origin) {
		if (errors.hasErrors())
			return "/user/signIn";
		if (service.hasUser(user)) {
			session.setAttribute("user", user);
			return "redirect:" + origin;
		} else {
			model.addAttribute("msg", "Enter the correct information.");
			return "/user/signIn";
		}
	}

}
